//
//  ExhibitWorkDetailsViewController.m
//  ArtDog
//
//  Created by dllo on 16/9/19.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ExhibitWorkDetailsViewController.h"
#import "BaseTableView.h"
#import "UIImageView+WebCache.h"
#import "HLMacro.h"
#import "ZWYNetTool.h"
#import "ExhibitWorkDetailsMainModel.h"
#import "ExhibitWorkDetailsTopTableCell.h"
#import "ExhibitWorkUserInfoTableCell.h"
#import "NSString+Common.h"
#import "CommentList.h"
#import "CommentTableViewCell.h"
#import "CommentToolbar.h"
#import "Masonry.h"
#import "MineMainViewController.h"

@interface ExhibitWorkDetailsViewController ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, CommentToolbarDelegate>

@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong) UIImageView *topImageView;
@property (nonatomic, assign) CGFloat ratio;
@property (nonatomic, strong) ExhibitWorkDetailsMainModel *mainModel;
@property (nonatomic, strong) NSMutableArray *commentArray;
@property (nonatomic, strong) CommentToolbar *toolbar;

@property (nonatomic, copy) NSString *commentUrlString;

@end

@implementation ExhibitWorkDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createViews];
    [self createBottomView];
}

- (void)setUrlString:(NSString *)urlString
{
    _urlString = urlString;
    [self handleData];
}


- (void)handleCommentData
{
    
    [ZWYNetTool GET:_commentUrlString andBody:nil andHeader:HOSTHEADER andResponse:ZWYJSON andSuccessBlock:^(id result) {
         NSString *commentUrlString1 = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"exhibit", _mainModel.authorId == nil ? @"0" :[NSString stringWithFormat:@"%@", _mainModel.authorId], @"work", [NSString stringWithFormat:@"%@", _mainModel.idField], @"comments"] andParams:@{@"token": [NSString getUserDefaultToken]}];
        _commentArray = [NSMutableArray array];
        if ([result[@"data"] count] == 0 && [_commentUrlString isEqualToString:commentUrlString1]) {
             NSString *commentUrlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"exhibit", @"0", @"work", [NSString stringWithFormat:@"%@", _mainModel.idField], @"comments"] andParams:@{@"token": [NSString getUserDefaultToken]}];
            _commentUrlString = commentUrlString;
            [self handleCommentData];
        }
        for (NSDictionary *dic in result[@"data"]) {
            CommentList *commentModel = [CommentList modelWithDic:dic];
            [_commentArray addObject:commentModel];
        }
        [_tableView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)handleData {
    [ZWYNetTool GET:_urlString andBody:nil andHeader:HOSTHEADER andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _mainModel = [ExhibitWorkDetailsMainModel modelWithDic:result[@"data"]];
        [self addDataForViews];
        NSString *commentUrlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"exhibit", _mainModel.authorId == nil ? @"0" :[NSString stringWithFormat:@"%@", _mainModel.authorId], @"work", [NSString stringWithFormat:@"%@", _mainModel.idField], @"comments"] andParams:@{@"token": [NSString getUserDefaultToken]}];
        _commentUrlString = commentUrlString;
        [self handleCommentData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

- (void)addDataForViews
{
    [_topImageView sd_setImageWithURL:[NSURL URLWithString:_mainModel.worksPic] placeholderImage:[UIImage imageNamed:@"placeholder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        _ratio = image.size.width / image.size.height;
        _topImageView.frame = CGRectMake(0, -64, SCREEN_WIDTH, SCREEN_WIDTH / _ratio);
        [_tableView reloadData];
    }];
}

- (void)createViews
{
    _topImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, -64, SCREEN_WIDTH, 300)];
    [self.view addSubview:_topImageView];
    _topImageView.image = [UIImage imageNamed:@"placeholder"];
    _topImageView.clipsToBounds = YES;
    _topImageView.userInteractionEnabled = YES;
    _topImageView.contentMode = UIViewContentModeScaleAspectFill;
    _ratio = 1;
    _ratio = _topImageView.image.size.width / _topImageView.image.size.height;
    _topImageView.frame = CGRectMake(0, -64, SCREEN_WIDTH, SCREEN_WIDTH / _ratio);
    
    _tableView = [[BaseTableView alloc]initWithFrame:CGRectMake(0, -64, SCREEN_WIDTH, SCREEN_HEIGHT - 49) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"aaa"];
    [_tableView registerNib:[UINib nibWithNibName:@"ExhibitWorkDetailsTopTableCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"exhibitWorkDetailsTopTableCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"ExhibitWorkUserInfoTableCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"exhibitWorkUserInfoTableCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"CommentTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"commentTableViewCell"];
}

- (void)createBottomView
{
    _toolbar = [[CommentToolbar alloc]init];
    [self.view addSubview:_toolbar];
    _toolbar.backgroundColor = [UIColor whiteColor];
    [_toolbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(_tableView.mas_bottom).offset(49);
    }];
    _toolbar.delegate = self;
    _toolbar.leftImageView.hidden = YES;
    _toolbar.sendBtn.hidden = YES;
    [_toolbar.sendBtn removeFromSuperview];
    [_toolbar.leftImageView removeFromSuperview];
    
    // 键盘
    UIView *freeKBView = [[UIView alloc]init];
    [self.view addSubview:freeKBView];
    [freeKBView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.bottom.equalTo(_toolbar.mas_top);
    }];
    freeKBView.backgroundColor = [UIColor clearColor];
    freeKBView.hidden = YES;
    
    __weak typeof (self) weakSelf = self;
    [self setKeyboard:^(NSNotification *noti, CGFloat height) {
        [weakSelf.toolbar mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf.view);
            make.bottom.equalTo(weakSelf.tableView.mas_bottom).offset(49 - height);
        }];
        freeKBView.hidden = NO;
        [weakSelf createTapGesture:freeKBView];
        
    } andWillHide:^(NSNotification *noti) {
        [weakSelf.toolbar mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf.view);
            make.bottom.equalTo(weakSelf.tableView.mas_bottom).offset(49);
        }];
        freeKBView.hidden = YES;
    }];
}

#pragma toolbar 发表评论 toolbar delegate
- (void)sendCommentFromeKeyboard:(UITextView *)textView
{
    //api.artgoer.cn:8084/artgoer/api/v1/user/271803/exhibit/0/work/57019/addComment
    NSRange range = [_commentUrlString rangeOfString:@"exhibit"];
    NSInteger index = range.location + range.length + 1;
    NSString *urlString = @"";
    if ([[_commentUrlString substringWithRange:NSMakeRange(index, 2)] isEqualToString:@"0/"]) {
        urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"exhibit", @"0", @"work", [NSString stringWithFormat:@"%@", _mainModel.idField], @"addComment"] andParams:@{@"token": [NSString getUserDefaultToken], @"topicType": @"6", @"commentText": textView.text}];
    } else {
        urlString = [NSString getURLStringWith:HOST andPaths:@[@"artgoer/api/v1/user", [NSString getUserDefaultId], @"exhibit", _mainModel.authorId == nil ? @"0" :[NSString stringWithFormat:@"%@", _mainModel.authorId], @"work", [NSString stringWithFormat:@"%@", _mainModel.idField], @"addComment"] andParams:@{@"token": [NSString getUserDefaultToken], @"topicType": @"6", @"commentText": textView.text}];
    }
    
    [ZWYNetTool POST:urlString andBody:nil andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type": @"application/x-www-form-urlencoded", @"Host": @"api.artgoer.cn:8084"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        CommentList *model = [CommentList modelWithDic:result[@"data"]];
        [_commentArray insertObject:model atIndex:0];
        [_tableView reloadData];
        textView.text = nil;
        [textView resignFirstResponder];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    }];

}
#pragma mark - 释放键盘手势
- (void)createTapGesture:(UIView *)freeView
{
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [freeView addGestureRecognizer:tapGesture];
}
- (void)tapAction
{
    [_toolbar.textView resignFirstResponder];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y <= SCREEN_WIDTH / _ratio) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        _topImageView.frame = CGRectMake(0, - 64, SCREEN_WIDTH, -scrollView.contentOffset.y + SCREEN_WIDTH / _ratio);
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (_topImageView.frame.size.height > SCREEN_WIDTH / _ratio) {
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            _topImageView.frame = CGRectMake(0, - 64, SCREEN_WIDTH, SCREEN_WIDTH / _ratio);
        } completion:^(BOOL finished) {
            
        }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_commentArray.count == 0) {
        return 4;
    }
    return _commentArray.count + 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aaa"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.text = @"";
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    } else if (indexPath.row == 1) {
        ExhibitWorkDetailsTopTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"exhibitWorkDetailsTopTableCell"];
        cell.detailsModel = _mainModel;
        return cell;
    } else if (indexPath.row == 2) {
        ExhibitWorkUserInfoTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"exhibitWorkUserInfoTableCell"];
        cell.detailsModel = _mainModel;
        return cell;
    } else {
        if (_commentArray.count != 0) {
            CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentTableViewCell"];
            cell.commentModel = _commentArray[indexPath.row - 3];
            return cell;
        } else {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aaa"];
            cell.textLabel.text = @"终于等到你来评论！";
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1];
            return cell;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return SCREEN_WIDTH / _ratio;
    } else if (indexPath.row == 1) {
        return 200;
    } else if (indexPath.row == 2) {
        return 80;
    } else {
        if (_commentArray.count == 0) {
            return 100;
        }
        return [CommentTableViewCell getHeight];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
